#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h> //sockaddr_in
#include <arpa/inet.h>

#define PORT 6679

int main()
{
  int socket_fd;
  int new_fd;

  socket_fd=socket(AF_INET,SOCK_STREAM,0);// int socket(int domain, int type, int protocol);
  printf("socket_fd is %d\n",socket_fd);
            
  struct sockaddr_in server_addr;

  memset(&server_addr,0,sizeof(server_addr));
  server_addr.sin_family=AF_INET;
  server_addr.sin_port=htons(PORT);
  server_addr.sin_addr.s_addr=htonl(INADDR_ANY);
  memset(&(server_addr.sin_zero),0,8);

  int contain;
  setsockopt(socket_fd,SOL_SOCKET, SO_REUSEADDR, &contain, sizeof(int));
            

  int res=bind(socket_fd,(struct sockaddr *)&server_addr,sizeof(server_addr));
  printf("bind res is %d\n",res);
  if(res==-1)
    return -1;

  if(listen(socket_fd,20)==-1)
    {
      printf("Failed to listen!\n");
      return -1;
    }
  printf("after listen\n");

  while(1)
    {
      struct sockaddr_in client_addr;
      socklen_t size=sizeof(client_addr);
      new_fd=accept(socket_fd, (struct sockaddr *)&client_addr, &size);
      if(new_fd==-1)
        {
          printf("wait for client to connect!\n");
          sleep(1);
          continue;
        }
      printf("A connect and the new fd is %d\n",new_fd);
      //while(1)
      {
        FILE *in;
        char input[100];
        res=read(new_fd,input,100);
        input[res]=0;
        char path[100];
        sprintf(path,"/c/download/%s",input);
        printf("the path is %s\n",path);
        in=fopen(path,"w");
        printf("after path\n");

        int fileLen = 0;
        int readLen = 0;
        res = read(new_fd,&fileLen,4);

        printf("\nGetFileLen is %d\n",fileLen);
        char buffer[8192];
        while(1)
          {
            res=read(new_fd,buffer,8192);
            readLen += res;
            printf("%d\n",readLen);
            fwrite(buffer,sizeof(char),res,in);
            if(readLen >= fileLen)
              {
                return 0;
              }

          }
      }
    }
  close(socket_fd);
  close(new_fd);
  return 0;
}
